package com.travel.service;

import java.awt.Font;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;

import com.travel.core.DaoFactory;
import com.travel.dao.ISpotDao;

public class DrawLine {
	private String cityCode;
	private int selectedType;
	private List<String> years;
	private String SpotName = "桂林市";
	private ChartPanel frame1;
	private static final ISpotDao SPOT_DAO = DaoFactory.getDao(ISpotDao.class);

	public DrawLine(String cityCode, String spotName, List<String> years, int selectedType) {
		this.SpotName = spotName;
		this.years = years;
		this.cityCode = cityCode;
		this.selectedType = selectedType;
		XYDataset xydataset = createDatasets(years.size());
		yearSpotLine(xydataset);
	}

	// 查询某一年的游客数量统计信息
	public JFreeChart yearSpotLine(XYDataset xydataset) {
		JFreeChart jfreechart = ChartFactory.createTimeSeriesChart(SpotName + "游客人流量折线图", "月份", "游客人流量", xydataset,
				true, true, true);
		XYPlot xyplot = (XYPlot) jfreechart.getPlot();
		DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
		dateaxis.setDateFormatOverride(new SimpleDateFormat("MMM"));
		frame1 = new ChartPanel(jfreechart, true);
		dateaxis.setLabelFont(new Font("黑体", Font.BOLD, 14)); // 水平底部标题
		dateaxis.setTickLabelFont(new Font("宋体", Font.BOLD, 12)); // 垂直标题
		ValueAxis rangeAxis = xyplot.getRangeAxis();// 获取柱状
		rangeAxis.setLabelFont(new Font("黑体", Font.BOLD, 15));
		jfreechart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 15));
		jfreechart.getTitle().setFont(new Font("宋体", Font.BOLD, 20));// 设置标题字体
		return jfreechart;
	}

	// 获取3年内的数据集
	public XYDataset createDatasets(int n) { // 获取一年的数据集
		List<Map<String, Object>> yearCount = SPOT_DAO.getStaticticsByCityOrSpotYear(cityCode, years, selectedType);
		TimeSeriesCollection timeseriescollection = new TimeSeriesCollection();
		int newyear = Integer.valueOf(years.get(0));
		for (String year : years) {
			TimeSeries timeseries = new TimeSeries(year + "年月游客数量");
			for (Map<String, Object> ymMap : yearCount) {
				if (ymMap.get("ym").toString().split("-")[0].equals(year)) {
					int val = Integer.parseInt(ymMap.get("count").toString());
					timeseries.add(new Month(Integer.valueOf(ymMap.get("ym").toString().split("-")[1]), newyear), val);
				}
			}
			timeseriescollection.addSeries(timeseries);
		}
		return timeseriescollection;
	}

	public ChartPanel getChartPanel() {
		return frame1;
	}
}
